import React, { useState, useRef, useEffect } from 'react';
import TodoButton from './TodoButton/TodoButton';
import TodoList from './TodoList';
import TodoModal from './TodoModal/TodoModal'
import '../assets/css/todo.css';

export default function Todo() {
  const [text, setText] = useState('');
  const [todoList, setTodoList] = useState([]);
  const [editTodo, setEditTodo] = useState({});
  const myRef = useRef();

  const onTodoTextChange = (e) => {
    setText(e.target.value)
  }

  const onAddTodo = () => {
    const todo = {
      id: Date.now(),
      text
    }
    setTodoList([...todoList, todo])
    setText('')
  }

  const delTodo = (id) => {
    const newTodoList = todoList.filter(item => item.id != id)
    setTodoList(newTodoList)
  }

  // 打开编辑模态框
  const onEdit = (id) => {
    console.log('编辑的id', id)
    const todo = todoList.find(item => item.id == id);
    // console.log(todo);
    setEditTodo(todo)
    setVisible(true);
  }

  // 编辑
  const onEditTodo = (e) => {
    setEditTodo({
      ...editTodo,
      text: e.target.value
    })
  }

  useEffect(() => {
    myRef.current.focus();
  }, [])

  const [visible, setVisible] = useState(false);
  const onConfirm = () => {
    setVisible(false);
    const t = todoList.map(item => {
      if (item.id == editTodo.id) {
        item.text = editTodo.text
      }
      return item;
    })
    setTodoList(t);
    setEditTodo({});
  }
  const onClose = () => {
    setVisible(false);
  }

  return (
    <div className='todo'>
      {/* 输入框部分 */}
      <div className='todo-form'>
        <input ref={myRef} className='todo-input' type="text" placeholder='请输入待办事项' value={text} onChange={onTodoTextChange} />
        <TodoButton type="primary" onClick={onAddTodo}>新增</TodoButton>
      </div>

      <TodoList
        data={todoList}
        right={(item) => (
          <>
            <TodoButton onClick={() => onEdit(item.id)}>编辑</TodoButton>
            <TodoButton onClick={() => delTodo(item.id)}>删除</TodoButton>
          </>
        )}>
      </TodoList>

      <TodoModal visible={visible} title="编辑" onClose={onClose} onConfirm={onConfirm}>
        <div>
          <input value={editTodo.text} onChange={onEditTodo} placeholder='请输入要编辑的内容' />
        </div>
      </TodoModal>
    </div >
  )
}
